//
//  SplashScreenViewController.m
//  Mehfile Zainab
//
//  Created by Sitara Badourali on 28/01/12.
//  Copyright 2012 CFA de Bobigny - COIFFURE. All rights reserved.
//

#import "SplashScreenViewController.h"
#import "FileManager.h"
#import "MainXMLParser.h"
#import <AudioToolbox/AudioToolbox.h>

/* cache update interval in seconds */
//const double MZCacheInterval = 86400.0;
const double MZCacheInterval = 120.0;

@interface NSObject (PrivateMethods)

- (void) getFileModificationDate;
- (void) loadDataWithURL:(NSURL *)theURL;

@end

@implementation SplashScreenViewController

@synthesize activityIndicator;

@synthesize dataPath;
@synthesize urlArray;
@synthesize filePath;
@synthesize fileDate;
@synthesize connection;
@synthesize XMLParsed;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
		
    XMLParsed = FALSE;
    
	/*
	 Once view is loaded, we give job to a new thread :
	 - animate the activity indicator for indicating that application is loading
	 - load/initialize any necessary data for application
	*/
	[NSThread detachNewThreadSelector:@selector(threadStartLoading:) toTarget:self withObject:nil];
	
}

-(void)threadStartLoading:(id)data
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
    NSLog(@"Start loading indicator animation");
	[self.activityIndicator startAnimating];
    
	/*
	 Only main thread can perform action on GUI.
     */
    [self performSelectorOnMainThread:@selector(threadEndLoading:) withObject:nil waitUntilDone:YES];
    
	[pool drain];
	
}

-(void)threadEndLoading:(id)data
{
    
    [self doBackgroundWork];
    
}

-(void)doBackgroundWork {
    
    NSLog(@"Background work in progress...");
    
    /* By default, the Cocoa URL loading system uses a small shared memory cache.
	 We don't need this cache, so we set it to zero when the application launches. */
    
    NSLog(@"Turn off the NSURLCache shared cache");
    
    NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0
                                                            diskCapacity:0
                                                                diskPath:nil];
    [NSURLCache setSharedURLCache:sharedCache];
    [sharedCache release];
    
	[self initCache];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"MZCache" ofType:@"plist"];
    if (path) {
        NSArray *array = [[NSArray alloc] initWithContentsOfFile:path];
        self.urlArray = [NSMutableArray array];
        for (NSString *element in array) {
            [self.urlArray addObject:[NSURL URLWithString:element]];
        }
        [array release];
    }
    NSLog(@"Get the URL information from property list : %@",[self.urlArray objectAtIndex:0]);
    
	[self loadDataWithURL:[urlArray objectAtIndex:0]];
    
    NSLog(@"Background work ended");
    
}

- (void)parseXMLFile {
    
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:
                              [[NSData alloc] initWithContentsOfFile:[FileManager getCachedDataFile]]];
    
    MainXMLParser *parser = [[MainXMLParser alloc] initXMLParser:self];
    
    [xmlParser setDelegate:parser];
    
    BOOL success = [xmlParser parse];
    
    if(success)
        NSLog(@"No Errors");
    else
        NSLog(@"Error when parsing XML file!");
    
}

- (void) initCache
{
    NSLog(@"Prepare to use our own on-disk cache");
    
	/* create path to cache directory inside the application's Documents directory */
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    self.dataPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"MZCache"];
    
	NSLog(@"Initializing cache, value of dataPath : %@",self.dataPath);
	
	/* check for existence of cache directory */
	if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
		return;
	}
    
	/* create a new cache directory */
	if (![[NSFileManager defaultManager] createDirectoryAtPath:dataPath
								   withIntermediateDirectories:NO
													attributes:nil
														 error:&error]) {
		NSLog(@"Error when creating on-disk cache directory : %@",error);
		return;
	}
}

/* get modification date of the current cached image */

- (void) getFileModificationDate
{
    
    NSLog(@"Check the last modified date of the data to see if we need to load a new version");
    
	/* default date if file doesn't exist (not an error) */
	self.fileDate = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
		/* retrieve file attributes */
		NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:&error];
		if (attributes != nil) {
			self.fileDate = [attributes fileModificationDate];
		}
		else {
            NSLog(@"Error while checking file attribute of : %@ [ %@ ]",filePath,error);
		}
	}
}

- (void) loadDataWithURL:(NSURL *)theURL
{
    
    NSLog(@"Load new or existing cached data");
    
	[filePath release]; /* release previous instance */
	NSString *fileName = [[theURL path] lastPathComponent];
	filePath = [[dataPath stringByAppendingPathComponent:fileName] retain];
    NSLog(@"Get the path to the cached data : %@",filePath);
    
    /*
	[self getFileModificationDate];
	// get the elapsed time since last file update
	NSTimeInterval time = fabs([fileDate timeIntervalSinceNow]);
	if (time > MZCacheInterval) {
		// file doesn't exist or hasn't been updated for at least one day
		self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
	}
	else {
		NSLog(@"Previously cached data found in cache and updated in last 24 hours.");
        [self endLoading];
	}
    */
    
    self.connection = [[URLCacheConnection alloc] initWithURL:theURL delegate:self];
    
}


-(void)endLoading {

    if (!XMLParsed) {
        
        XMLParsed = TRUE;
        
        [self parseXMLFile];
        
        //NSLog(@"********** Sleep : TO BE REMOVED **********");
        //[NSThread sleepForTimeInterval:3];
        
        NSLog(@"Stop loading indicator animation");
        [self.activityIndicator stopAnimating];
        [self.activityIndicator release];
        
        NSLog(@"Dismiss Splash Screen modal view");
        //[self dismissModalViewControllerAnimated:YES];
        [self dismissViewControllerAnimated:YES completion:nil];
        
        //[self activatePushNotification];
        
    }

}

/*
-(void)activatePushNotification {
    
    NSLog(@"Registering for Push notifications");
    
    // Add registration for remote notifications
    [[UIApplication sharedApplication]
     registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
    
    // Clear application badge when app launches
    UIApplication *application = [UIApplication sharedApplication];
    application.applicationIconBadgeNumber = 0;

}
*/

/*
 * ------------------------------------------------------------------------------------------
 *  BEGIN APNS CODE
 * ------------------------------------------------------------------------------------------
 */

/**
 * Fetch and Format Device Token and Register Important Information to Remote Server
 */

/*
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
    
    NSLog(@"My token is: %@", devToken);
    
#if !TARGET_IPHONE_SIMULATOR
    
    NSLog(@"My token is: %@", devToken);
    
	// Get Bundle Info for Remote Registration (handy if you have more than one app)
	NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
	NSString *appVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
	// Check what Notifications the user has turned on.  We registered for all three, but they may have manually disabled some or all of them.
	NSUInteger rntypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
    
	// Set the defaults to disabled unless we find otherwise...
	NSString *pushBadge = @"disabled";
	NSString *pushAlert = @"disabled";
	NSString *pushSound = @"disabled";
    
	// Check what Registered Types are turned on. This is a bit tricky since if two are enabled, and one is off, it will return a number 2... not telling you which
	// one is actually disabled. So we are literally checking to see if rnTypes matches what is turned on, instead of by number. The "tricky" part is that the
	// single notification types will only match if they are the ONLY one enabled.  Likewise, when we are checking for a pair of notifications, it will only be
	// true if those two notifications are on.  This is why the code is written this way
	if(rntypes == UIRemoteNotificationTypeBadge){
		pushBadge = @"enabled";
	}
	else if(rntypes == UIRemoteNotificationTypeAlert){
		pushAlert = @"enabled";
	}
	else if(rntypes == UIRemoteNotificationTypeSound){
		pushSound = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert)){
		pushBadge = @"enabled";
		pushAlert = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)){
		pushBadge = @"enabled";
		pushSound = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)){
		pushAlert = @"enabled";
		pushSound = @"enabled";
	}
	else if(rntypes == ( UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)){
		pushBadge = @"enabled";
		pushAlert = @"enabled";
		pushSound = @"enabled";
	}
    
	// Get the users Device Model, Display Name, Unique ID, Token & Version Number
	UIDevice *dev = [UIDevice currentDevice];
	NSString *deviceUuid = dev.uniqueIdentifier;
    NSString *deviceName = dev.name;
	NSString *deviceModel = dev.model;
	NSString *deviceSystemVersion = dev.systemVersion;
    
	// Prepare the Device Token for Registration (remove spaces and < >)
	NSString *deviceToken = [[[[devToken description]
                               stringByReplacingOccurrencesOfString:@"<"withString:@""]
                              stringByReplacingOccurrencesOfString:@">" withString:@""]
                             stringByReplacingOccurrencesOfString: @" " withString: @""];
    
	// Build URL String for Registration
	// !!! CHANGE "www.mywebsite.com" TO YOUR WEBSITE. Leave out the http://
	// !!! SAMPLE: "secure.awesomeapp.com"
	NSString *host = @"192.168.0.27:8888";
    //NSString *host = @"sitara.azad.free.fr";
    
	// !!! CHANGE "/apns.php?" TO THE PATH TO WHERE apns.php IS INSTALLED
	// !!! ( MUST START WITH / AND END WITH ? ).
	// !!! SAMPLE: "/path/to/apns.php?"
	NSString *urlString = [@"/imzpush/apns.php?"stringByAppendingString:@"task=register"];
    //NSString *urlString = [@"/iosmehfile/imzpush/apns.php?"stringByAppendingString:@"task=register"];
    
	urlString = [urlString stringByAppendingString:@"&appname="];
	urlString = [urlString stringByAppendingString:appName];
	urlString = [urlString stringByAppendingString:@"&appversion="];
	urlString = [urlString stringByAppendingString:appVersion];
	urlString = [urlString stringByAppendingString:@"&deviceuid="];
	urlString = [urlString stringByAppendingString:deviceUuid];
	urlString = [urlString stringByAppendingString:@"&devicetoken="];
	urlString = [urlString stringByAppendingString:deviceToken];
	urlString = [urlString stringByAppendingString:@"&devicename="];
	urlString = [urlString stringByAppendingString:deviceName];
	urlString = [urlString stringByAppendingString:@"&devicemodel="];
	urlString = [urlString stringByAppendingString:deviceModel];
	urlString = [urlString stringByAppendingString:@"&deviceversion="];
	urlString = [urlString stringByAppendingString:deviceSystemVersion];
	urlString = [urlString stringByAppendingString:@"&pushbadge="];
	urlString = [urlString stringByAppendingString:pushBadge];
	urlString = [urlString stringByAppendingString:@"&pushalert="];
	urlString = [urlString stringByAppendingString:pushAlert];
	urlString = [urlString stringByAppendingString:@"&pushsound="];
	urlString = [urlString stringByAppendingString:pushSound];
    
	// Register the Device Data
	// !!! CHANGE "http" TO "https" IF YOU ARE USING HTTPS PROTOCOL
	NSURL *url = [[NSURL alloc] initWithScheme:@"http" host:host path:urlString];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
	NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
	NSLog(@"Register URL: %@", url);
	NSLog(@"Return Data: %@", returnData);
    
#endif
}
*/

/**
 * Failed to Register for Remote Notifications
 */
/*
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    
#if !TARGET_IPHONE_SIMULATOR
    
	NSLog(@"Error in registration. Error: %@", error);
    
#endif
}
*/

/**
 * Remote Notification Received while application was open.
 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
#if !TARGET_IPHONE_SIMULATOR
    
	NSLog(@"Remote notification: %@",[userInfo description]);
	NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];
    
	NSString *alert = [apsInfo objectForKey:@"alert"];
	NSLog(@"Received Push Alert: %@", alert);
    
	NSString *sound = [apsInfo objectForKey:@"sound"];
	NSLog(@"Received Push Sound: %@", sound);
	AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
	NSString *badge = [apsInfo objectForKey:@"badge"];
	NSLog(@"Received Push Badge: %@", badge);
	application.applicationIconBadgeNumber = [[apsInfo objectForKey:@"badge"] integerValue];
    
#endif
}

/*
 * ------------------------------------------------------------------------------------------
 *  END APNS CODE
 * ------------------------------------------------------------------------------------------
 */

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


/*
 ------------------------------------------------------------------------
 URLCacheConnectionDelegate protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark URLCacheConnectionDelegate methods

- (void) connectionDidFail:(URLCacheConnection *)theConnection
{
    NSLog(@"Connection failed!");
    [self endLoading];
    
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"Mehfile Zainab" message:@"Connexion impossible, merci de réessayer plus tard." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    
}


- (void) connectionDidFinish:(URLCacheConnection *)theConnection
{
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == YES) {
        
        /*
		// apply the modified date policy
		[self getFileModificationDate];
		NSComparisonResult result = [theConnection.lastModified compare:fileDate];
		if (result == NSOrderedDescending) {
			// file is outdated, so remove it
			if (![[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]) {
                NSLog(@"Error while removing item at path : %@ [ %@ ]",filePath,error);
			}
            
		}
        */
        
        NSLog(@"Application launch, clear cache because connection was successful");
        
        for (NSString *file in [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.dataPath error:&error]) {
            NSString *fileToDelete = [[self.dataPath stringByAppendingPathComponent:file] retain];
            NSLog(@"Delete file : %@",fileToDelete);
            BOOL success = [[NSFileManager defaultManager] removeItemAtPath:fileToDelete error:&error];
            if (!success || error) {
                NSLog(@"Error when deleting data : %@",fileToDelete);
            }
        }
        
	}
    
	if ([[NSFileManager defaultManager] fileExistsAtPath:filePath] == NO) {
		/* file doesn't exist, so create it */
		[[NSFileManager defaultManager] createFileAtPath:filePath
												contents:theConnection.receivedData
											  attributes:nil];
        
		NSLog(@"Newly cached data because data not found in cache or new data available : %@",filePath);
	}
	else {
		NSLog(@"Cached data is up to date : data updated and no new data available : %@",filePath);
	}
    
	/* reset the file's modification date to indicate that the URL has been checked */
    
	NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSDate date], NSFileModificationDate, nil];
	if (![[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:filePath error:&error]) {
		NSLog(@"Error while setting file attribute on : %@ [ %@ ]",filePath,error);
	}
	[dict release];
    
    [self endLoading];
    
}


@end
